// pages/detail/detail.js
Page({
  data: {
    pageTitle: '绘本详情',
    currentSort: 'default',
    sortTabs: [
      { label: '默认', value: 'default' },
      { label: '时间', value: 'time' },
      { label: '热度', value: 'popular' }
    ],
    books: [],
    currentPage: 1,
    totalPages: 1,
    pageSize: 12
  },

  onLoad(options) {
    // 获取页面参数
    const { id, title } = options
    this.setData({
      pageTitle: title || '绘本详情'
    })
    
    this.loadBooks()
  },

  // 加载书籍数据
  loadBooks() {
    // 模拟数据
    const mockBooks = []
    for (let i = 1; i <= 24; i++) {
      mockBooks.push({
        id: i,
        title: `绘本${i}`,
        author: `作者${i}`,
        pages: Math.floor(Math.random() * 20) + 10,
        status: Math.random() > 0.5 ? 'completed' : 'uncompleted',
        theme: (i % 5) + 1,
        createTime: Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000,
        popularity: Math.floor(Math.random() * 100)
      })
    }
    
    this.setData({
      books: mockBooks,
      totalPages: Math.ceil(mockBooks.length / this.data.pageSize)
    })
    
    this.sortBooks()
  },

  // 排序书籍
  sortBooks() {
    let sortedBooks = [...this.data.books]
    
    switch (this.data.currentSort) {
      case 'time':
        sortedBooks.sort((a, b) => b.createTime - a.createTime)
        break
      case 'popular':
        sortedBooks.sort((a, b) => b.popularity - a.popularity)
        break
      default:
        // 默认排序，保持原顺序
        break
    }
    
    this.setData({
      books: sortedBooks
    })
  },

  // 排序标签点击
  onSortTap(e) {
    const sort = e.currentTarget.dataset.sort
    this.setData({
      currentSort: sort
    })
    this.sortBooks()
  },

  // 书籍点击
  onBookTap(e) {
    const book = e.currentTarget.dataset.book
    wx.navigateTo({
      url: `/pages/reading/reading?id=${book.id}&title=${book.title}`
    })
  },

  // 操作按钮点击
  onActionTap(e) {
    const { action, id } = e.currentTarget.dataset
    
    switch (action) {
      case 'favorite':
        wx.showToast({
          title: '已添加到收藏',
          icon: 'success'
        })
        break
      case 'share':
        wx.showShareMenu({
          withShareTicket: true,
          menus: ['shareAppMessage', 'shareTimeline']
        })
        break
    }
  },

  // 上一页
  prevPage() {
    if (this.data.currentPage > 1) {
      this.setData({
        currentPage: this.data.currentPage - 1
      })
    }
  },

  // 下一页
  nextPage() {
    if (this.data.currentPage < this.data.totalPages) {
      this.setData({
        currentPage: this.data.currentPage + 1
      })
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack()
  },

  // 页面分享
  onShareAppMessage() {
    return {
      title: `${this.data.pageTitle} - 儿童英语分级阅读`,
      path: '/pages/detail/detail'
    }
  }
}) 